import { messages, getDefaultSetOfBook } from "share/common";
import React from "react";
import { connect } from "react-redux";
import {
  Tabs,
  Popover,
  Menu,
  Divider,
  Dropdown,
  Button,
  Icon,
  message,
} from "antd";
import configureStore from "stores";
import { setDefaultSetOfBook } from "actions/cache";
import SearchArea from "components/search-area";
import ListSelector from "components/list-selector";
import ResizeTable from "components/resize-table";
import SlideFrame from "components/slide-frame";
import ExpenseTypeRenderer from "components/ExpenseTypeRenderer";
import ExpenseAmountForm from "./ExpenseAmountForm";
import ExpenseAmountNewForm from "./ExpenseAmountNewForm";
import service from "./service";
import {
  getClassifyTypeSearchItem,
  getCycleSearchItem,
  getCycleLabel,
  getClassifyTypeLabel,
} from "./config";

const { TabPane } = Tabs;

class ExpenseStandard extends React.Component {
  loading = false;

  constructor(props) {
    super(props);
    const setOfBooksId =
      props.expenseTypeSetOfBooks.id || props.company.setOfBooksId;
    this.state = {
      searchParams: {
        expenseTypeOid: undefined,
        cycle: undefined,
        classifyType: undefined,
        page: 0,
      },
      searchForm: [
        // 费用类型
        {
          type: "list",
          listType: "selectInvoiceType",
          // listType: 'invoice_budget',
          options: [],
          valueKey: "expenseTypeOID",
          labelKey: "name",
          listExtraParams: {
            enabled: true,
            setOfBooksId,
            subsidyType: 0,
          },
          single: true,
          id: "expenseTypeOid",
          label: messages("budget-setting.key85" /* 费用类型 */),
        },
        // 分类
        getClassifyTypeSearchItem(),
        // 周期
        getCycleSearchItem(),
      ],

      loading: false,
      data: [],
      showSlideEditFrame: false,
      showSlideFrame: false,
      setOfBooksId,
      editRecord: null,
      columns: [
        {
          title: messages("setting.key1090" /* 费用类型 */),
          dataIndex: "name",
          render: (text) => (
            <Popover placement="topLeft" content={text}>
              {text}
            </Popover>
          ),
        },
        {
          title: "分类",
          dataIndex: "classifyType",
          render: (text) => (
            <Popover placement="topLeft" content={getClassifyTypeLabel(text)}>
              {getClassifyTypeLabel(text)}
            </Popover>
          ),
        },
        {
          title: "周期",
          dataIndex: "cycle",
          render: (text) => (
            <Popover placement="topLeft" content={getCycleLabel(text)}>
              {getCycleLabel(text)}
            </Popover>
          ),
        },
        {
          title: messages("common.operation" /* 操作 */),
          dataIndex: "operation",
          render: (text, record) => (
            <span>
              <a disabled={record.forbiddenFlag} onClick={(e) => this.edit(e, record)}>
                {messages("common.edit")}
              </a>
              <Divider type="vertical" />
              <a disabled={record.forbiddenFlag} onClick={(e) => this.goDetail(e, record)}>
                {messages("common.detail")}
              </a>
              <Divider type="vertical" />
              <a disabled={record.forbiddenFlag} onClick={() => this.disabledData(record)}>
                {messages("common.disabled")}
              </a>
            </span>
          ),
        },
      ],
      total: 0,
      current: 1,
      pageSize: 10,
    };
  }

  componentDidMount() {
    this.search();
  }

  search = async (result) => {
    if (this.loading) return;
    this.loading = true;
    this.setState({ loading: true });
    const { searchParams: stateSearchParams } = this.state;
    try {
      const searchParams = { ...stateSearchParams, ...result };
      const res = await service.search({ ...searchParams });
      this.setState({
        data: res.data,
        loading: false,
        total: Number(res.headers["x-total-count"]),
      });
    } catch (e) {
      console.error(e);
    } finally {
      this.loading = false;
      this.setState({ loading: false });
    }
  };

  clear = () => {
    this.setState({
      data: [],
      total: 0,
      current: 1,
    });
  };

  goDetail = (e, record) => {
    e.preventDefault();
    this.context.router.push(
      `/main/expense-reimbursement-control/expense-amount/expense-amount-rule/${record.id}`
    );
  };

  edit = (e, editRecord) => {
    e.preventDefault();
    this.setState({
      showSlideEditFrame: true,
      editRecord,
    });
  };

  handleCreate = () => {
    this.setState({
      showSlideFrame: true,
    });
  };

  handleCloseSlide = (shouldRefresh) => {
    this.setState({
      showSlideEditFrame: false,
      showSlideFrame: false,
    });
    if (shouldRefresh) {
      this.search();
    }
  };

  onChangePaper = (e) => {
    let obj = this.state.searchParams;
    console.log(e);
    obj.page = e - 1;
    this.setState(
      {
        searchParams: obj,
        current: e,
      },
      () => {
        this.search();
      }
    );
  };

  disabledData = (record) => {
    // console.log('record', record)
    service.disabledQuota(record.id).then(res => {
      // console.log("res", res);
      if (res.status === 200) {
        message.success('禁用成功');
        this.search();
      }
    }).catch(err => {
      message.error(err)
    })
  }

  render() {
    const {
      showSlideEditFrame,
      searchForm,
      loading,
      data,
      columns,
      pagination,
      setOfBooksId,
      editRecord,
      showSlideFrame,
    } = this.state;

    return (
      <div>
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.clear}
        />
        <div style={{ margin: "10px 0" }}>
          {" "}
          {
            messages("setting.key1589", {
              arg1: this.state.total,
            }) /* 共搜索到{arg1}条数据 */
          }
        </div>
        <div className="table-header">
          <div className="table-header-buttons">
            <Button onClick={this.handleCreate} type="primary">
              新建
            </Button>
          </div>
        </div>
        <ResizeTable
          rowKey="id"
          loading={loading}
          dataSource={data}
          columns={columns}
          pagination={{
            total: this.state.total,
            current: this.state.current,
            pageSize: this.state.pageSize,
            onChange: this.onChangePaper,
          }}
          size="middle"
          bordered
        />
        <SlideFrame
          title="新建费用额度设置"
          show={showSlideFrame}
          content={ExpenseAmountNewForm}
          afterClose={this.handleCloseSlide}
          // onClose={this.handleSlideClose}
          params={{
            show: showSlideFrame,
            setOfBooksId,
          }}
        />
        <SlideFrame
          title="编辑额度设置"
          show={showSlideEditFrame}
          content={ExpenseAmountForm}
          afterClose={this.handleCloseSlide}
          // onClose={this.handleSlideClose}
          params={{
            record: editRecord,
            setOfBooksId,
          }}
        />
      </div>
    );
  }
}

ExpenseStandard.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    expenseTypeSetOfBooks: state.setting.expenseTypeSetOfBooks,
    tenantMode: state.main.tenantMode,
  };
}

export default connect(mapStateToProps)(ExpenseStandard);
